var utils = require('../../../../utils/util.js')
const {
	$Toast
} = require('../../../../dist/base/index');
let wechat = require('../../../../utils/wechat.js');
//获取应用实例
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		cardId: '',
		cardInfo: {}, //名片信息
		cityData: '',
		headImg: '',
		phone: '',
		cardForwardTitle: '', //转发标题
		cardForwardCoverUrl: '', //转发封面
		collectionData: {}, //收藏数据
		teamList: [], //所加入团队
		teamChooseData: [], //选择团队
		visibleTeamChoose: false, //团队选择框
		spinShow: true,
		cardDisplayTeamsStatus: 0, //是否显示当前团队
		isCollect: false, //是否已收藏
		unionId: '',
		zanImg: 'http://ii.sinelinked.com/miniProgramAssets/zan.png',
		isPoints: false,
		counter: {},
		zan_scale: false,
		cardTemplateType: 1, //模板类型
		cardtplStyle: '',
		currentUnionId: '',
		currentOpenId: '',
		shoucangImg: 'http://ii.sinelinked.com/miniProgramAssets/choucang.png',
		poster: false,
		poster_image: ""
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		var self = this
		var scenes = decodeURIComponent(options.scene)
		var cardId = options.cardId || scenes.split('=')[1]
		if (cardId) {
			this.setData({
				cardId: cardId
			})

		}
	},
	// 点击组件收藏
	onMyevent(props) {
		const {
			isCollect
		} = props.detail
		if (isCollect) {
			var shoucangImg = 'http://ii.sinelinked.com/miniProgramAssets/choucang_fill.png'
			this.setData({
				isCollect: true,
				shoucangImg: shoucangImg
			})
		} else {
			var shoucangImg = 'http://ii.sinelinked.com/miniProgramAssets/choucang.png'
			this.setData({
				isCollect: false,
				shoucangImg: shoucangImg
			})
		}

		this.getCounter()

	},
	// 判断名片是否已收藏
	isCollect(data) {
		return new Promise((resolve, reject) => {
			utils.request(utils.personApi + '/personal/card/holder/isCollect', 'GET', data)
				.then(res => {
					if (res.code == 0) {
						if (res.data.isCollect) {
							var shoucangImg = 'http://ii.sinelinked.com/miniProgramAssets/choucang_fill.png'
							this.setData({
								isCollect: true,
								shoucangImg: shoucangImg
							})

						} else {
							var shoucangImg = 'http://ii.sinelinked.com/miniProgramAssets/choucang.png'
							this.setData({
								isCollect: false,
								shoucangImg: shoucangImg
							})
						}
						resolve(res.data.isCollect)
					}
				})
		})
	},
	//获取信息
	getInfo(cardId, type = 1) {
		var self = this;
		var data = {
			cardId: cardId,
			type: type
		}
		utils.request(utils.personApi + '/personal/get/card/info', 'GET', data)
			.then((res) => {
				if (res.code == 0) {
					if (type == 1) {
						var cardInfo = res.data.info
						var counter = res.data.counter
						for (let val in cardInfo) {
							if (cardInfo[val] === null) {
								cardInfo[val] = ''
							}
						}

						var cardTemplateType = parseInt(cardInfo.cardTemplateType || 1)
						var cardtplStyle = 'mb-01-style'
						switch (cardTemplateType) {
							case 1:
								cardtplStyle = 'mb-01-style'
								break;
							case 2:
								cardtplStyle = 'mb-02-style'
								break;
							case 3:
								cardtplStyle = 'mb-03-style'
								break;
							default:
								break;
						}

						var currentUnionId = wx.getStorageSync('currentUnionId') //当前微信用户的unionId
						var currentOpenId = wx.getStorageSync('currentOpenId') //当前微信用户的openId
						this.setData({
							cardtplStyle,
							currentUnionId,
							currentOpenId
						})
						if (!currentOpenId) {
							wechat.getOpenIdOrUnionId()
								.then(res => {
									var data = res
									currentUnionId = data.unionId
									currentOpenId = data.openId

									var collectionData = {
										unionId: currentUnionId || '', //unionId
										openId: currentOpenId, //openId
										cardId: cardInfo.id, //名片id
										cardHeadUrl: cardInfo.cardHeadUrl,
										cardName: cardInfo.cardName, //名片姓名
										cardType: "1" //名片类型 ：1-个体  2-团队  3-商铺
									}
									var phone = self.formatPhone(cardInfo.cardPhone)
									self.setData({
										collectionData: collectionData,
									})

									// 判断当前名片是否已收藏
									self.isCollect({
										unionId: currentUnionId || '', //unionId
										openId: currentOpenId, //openId
										cardId: cardInfo.id, //名片id
										cardType: 1
									})

								})

						} else {
							var collectionData = {
								unionId: currentUnionId || '', //unionId
								openId: currentOpenId, //openId
								cardId: cardInfo.id, //名片id
								cardHeadUrl: cardInfo.cardHeadUrl,
								cardName: cardInfo.cardName, //名片姓名
								cardType: "1" //名片类型 ：1-个体  2-团队  3-商铺
							}
							var phone = self.formatPhone(cardInfo.cardPhone)
							self.setData({
								collectionData: collectionData,
							})

							// 判断当前名片是否已收藏
							self.isCollect({
								unionId: currentUnionId || '', //unionId
								openId: currentOpenId, //openId
								cardId: cardInfo.id, //名片id
								cardType: 1
							})

						}

						self.isPoints()

						self.setData({
							cardInfo,
							counter,
							phone: phone,
							['cardInfo.cardHeadUrl']: cardInfo.cardHeadUrl + '#&' + Math.random()
						})

						// 隐藏spin
						setTimeout(() => {
							this.setData({
								spinShow: false
							})
						}, 150)

						this.counter(1)


						try {
							// 	// 存储是非团队成员是否可以查看团队成员
							wx.setStorageSync('cardOthersDetailsStatus', cardInfo.cardOthersDetailsStatus)
							// 存储当前名片id
							wx.setStorageSync('activeCardId', cardInfo.id)
							// 存储当前名片头像
							if (cardInfo.cardHeadUrl) {
								wx.setStorageSync('headImg', cardInfo.cardHeadUrl + '#&' + Math.random())
							} else {
								wx.setStorageSync('headImg', 'http://ii.sinelinked.com/miniProgramAssets/defaultHeadImg.jpg')
							}
							// 存储当前名片转发相关信息
							if (cardInfo.cardForwardTitle) {
								wx.setStorageSync('cardForwardTitle', cardInfo.cardForwardTitle)
							} else {
								wx.setStorageSync('cardForwardTitle', '')
							}
							if (cardInfo.cardForwardCoverUrl) {
								wx.setStorageSync('cardForwardCoverUrl', cardInfo.cardForwardCoverUrl)
							} else {
								wx.setStorageSync('cardForwardCoverUrl', '')
							}
							const cardForwardTitle = wx.getStorageSync('cardForwardTitle')
							const cardForwardCoverUrl = wx.getStorageSync('cardForwardCoverUrl')

							if (cardForwardTitle) {
								self.setData({
									cardForwardTitle: cardForwardTitle
								})
							}
							if (cardForwardCoverUrl) {
								self.setData({
									cardForwardCoverUrl: cardForwardCoverUrl + '&' + Math.random()
								})
							}

						} catch (e) {
							console.log(e);
						}

					} else if (type == 4) {
						var teamList = res.data.teamList
						var tempArr = []
						teamList.map((item, index) => {
							tempArr.push({
								title: item.cardName,
								userId: item.id,
								id: index
							})
						})
						self.setData({
							teamList: teamList,
							teamChooseData: tempArr
						})
					}
				}



			})
	},
	// getCounter
	getCounter() {
		var data = {
			cardId: this.data.cardId,
			type: 1
		}
		utils.request(utils.personApi + '/personal/get/card/info', 'GET', data)
			.then((res) => {
				if (res.code == 0) {
					var counter = res.data.counter
					this.setData({
						counter
					})
				}
			})
	},
	// 统计收藏
	counter(type) {
		var data = {
			cardId: this.data.cardInfo.id,
			type: type
		}
		var requestUrl = utils.personApi + '/counter/refresh'
		utils.request(requestUrl, 'POST', data)
			.then(result => {
				if (type == 2) {
					this.getCounter()
				}
			})
			.catch(error => {
				console.log(error)
			})
	},
	// 全屏预览图片
	previewImages(e) {
		var self = this;
		wx.previewImage({
			current: self.data.cardInfo.cardHeadUrl,
			urls: [self.data.cardInfo.cardHeadUrl]
		})
	},
	//所属团队 
	getJoinedTeams(id) {

		var that = this
		wx.request({
			url: `https://ii.sinelinked.com/tg_web/api/user/XCX/getJoinedTeams`,
			data: {
				userId: id
			},
			success: function(res) {
				wx.hideNavigationBarLoading()
				if (res.data.code == 0) {
					that.setData({
						manyTeam: res.data.data
					})

					try {
						wx.setStorageSync('joinedTeams', res.data.data)
					} catch (e) {}


				}
			}
		})

	},
	// 播打电话
	makePhoneCall: function() {
		var that = this
		wx.makePhoneCall({
			phoneNumber: that.data.cardInfo.cardPhone
		})
	},
	toMsg: function() {
		utils.navigateTo({
			url: '/pages/card/person/msg/msg'
		})
	},
	tointroduce() {
		utils.navigateTo({
			url: '/pages/card/person/introduce/introduce?cardId=' + this.data.cardInfo.id
		})
	},
	tocompany() {
		utils.navigateTo({
			url: '/pages/card/person/company/company?cardId=' + this.data.cardInfo.id
		})
	},
	toshow() {
		utils.navigateTo({
			url: '/pages/card/person/show/show?cardId=' + this.data.cardInfo.id
		})
	},
	toTeam: function() {
		// 判断是否展示该团队
		if (this.data.cardInfo.cardDisplayTeamsStatus == 1) {
			wx.showToast({
				title: '该团队暂未开放',
				icon: 'none',
				duration: 2000
			})
			return
		}
		var teamList = this.data.teamList
		if (teamList.length == 1) {
			utils.navigateTo({
				url: '/pages/card/team/index/index?cardId=' + teamList[0].id
			})
		} else if (teamList.length > 1) {
			this.setData({
				visibleTeamChoose: true,
			})
		} else {
			wx.showToast({
				title: '还未加入任何团队',
				icon: 'none',
				duration: 2000
			})
		}
	},

	teamChooseHandle(e) {
		// var cardId = e.currentTarget.dataset.cardid
		var index = e.detail.index
		utils.navigateTo({
			url: '/pages/card/team/index/index?cardId=' + this.data.teamChooseData[index].userId
		})
	},
	// 格式化手机号码
	formatPhone: function(phone) {
		var phone = String(phone)
		if (phone) {
			return phone.slice(0, 3) + '-' + phone.slice(3, 7) + '-' + phone.slice(7, 11)
		}
	},
	// 点赞
	zanHandle() {
		var currentOpenId = wx.getStorageSync('currentOpenId')
		var data = {
			cardId: this.data.cardId,
			openId: currentOpenId
		}
		utils.request(utils.personApi + '/counter/points', 'POST', data)
			.then(res => {
				if (res.code == 0) {
					this.setData({
						zan_scale: true
					})
					this.isPoints()
					setTimeout(() => {
						this.setData({
							zan_scale: false
						})
					}, 1000)
				}
			})

	},
	// 收藏
	collectHandle() {
		var self = this
		// 判断当前名片是否已收藏
		this.isCollect({
				unionId: this.data.currentUnionId || '', //unionId
				openId: this.data.currentOpenId, //openId
				cardId: this.data.cardInfo.id, //名片id
				cardType: 1
			})
			.then(result => {
				if (result) {
					var data = this.data
					var data = {
						unionId: data.currentUnionId, //unionId
						openId: data.currentOpenId, //unionId
						cardId: data.cardId, //名片id
						cardType: 1 //名片类型 ：1-个体  2-团队  3-商铺
					}
					var requestUrl = utils.personApi + '/personal/card/holder/cancel'
					wx.showModal({
						title: '提示',
						content: '确定取消收藏',
						success(res) {
							if (res.confirm) {
								utils.request(requestUrl, 'POST', data)
									.then(res => {
										if (res.code == 0) {
											wx.showToast({
												title: '已取消收藏',
												icon: 'none',
												duration: 2000
											})
											// self.counter(2)
											self.getInfo(self.data.cardId)
											var shoucangImg = 'http://ii.sinelinked.com/miniProgramAssets/choucang.png'
											self.setData({
												isCollect: false,
												shoucangImg: shoucangImg
											})
										} else {
											wx.showToast({
												title: res.error,
												icon: 'none',
												duration: 2000
											})
										}
									})
							} else if (res.cancel) {

							}
						}
					})
				} else {
					var dataObj = this.data.cardInfo
					var data = {
						unionId: this.data.currentUnionId || '', //unionId
						openId: this.data.currentOpenId, //openId
						cardId: dataObj.id, //名片id
						cardHeadUrl: dataObj.cardHeadUrl,
						cardName: dataObj.cardName, //名片姓名
						cardType: "1" //名片类型 ：1-个体  2-团队  3-商铺
					}
					this.getUnionIdByOpenId()
						.then(unionId => {
							data.unionId = unionId
							var requestUrl = utils.personApi + '/personal/card/holder/collect'
							utils.request(requestUrl, 'POST', data)
								.then(res => {
									if (res.code == 0) {
										wx.showToast({
											title: '已收藏',
											icon: 'none',
											duration: 2000
										})
										var shoucangImg = 'http://ii.sinelinked.com/miniProgramAssets/choucang_fill.png'
										self.setData({
											isCollect: true,
											shoucangImg: shoucangImg
										})
										self.counter(2)
									} else {
										wx.showToast({
											title: res.error,
											icon: 'none',
											duration: 2000
										})
									}
								})
						})
						.catch(e => {
							var requestUrl = utils.personApi + '/personal/card/holder/collect'
							utils.request(requestUrl, 'POST', data)
								.then(res => {
									if (res.code == 0) {
										wx.showToast({
											title: '已收藏',
											icon: 'none',
											duration: 2000
										})
										var shoucangImg = 'http://ii.sinelinked.com/miniProgramAssets/choucang_fill.png'
										self.setData({
											isCollect: true,
											shoucangImg: shoucangImg
										})
										self.counter(2)
									} else {
										wx.showToast({
											title: res.error,
											icon: 'none',
											duration: 2000
										})
									}
								})
						})
				}
			})

	},
	// 根据当前微信用户openid获取unionId
	getUnionIdByOpenId() {
		return new Promise((resolve, reject) => {
			var data = {
				openId: this.data.data.openId,
				role: 1
			}
			utils.request(utils.personApi + '/personal/getUnionIdByOpenId', 'GET', data)
				.then(res => {
					var data = res.data

					if (data.unionId) {
						resolve(data.unionId)
					} else {
						reject(false)
					}
				})
		})
	},

	// 是否点赞
	isPoints() {
		var currentOpenId = wx.getStorageSync('currentOpenId')
		var data = {
			cardId: this.data.cardId,
			openId: currentOpenId
		}
		utils.request(utils.personApi + '/counter/isPoints', 'GET', data)
			.then(res => {
				if (res.code == 0) {
					var isPoints = res.data.isPoint == 'true' ? true : false
					var zanImg = isPoints ? 'http://ii.sinelinked.com/miniProgramAssets/zan_fill.png' :
						'http://ii.sinelinked.com/miniProgramAssets/zan.png'
					this.setData({
						isPoints: isPoints,
						zanImg: zanImg
					})
					this.getCounter()
				}
			})
	},

	// 下载图片
	downloadImg(link) {
		return new Promise((resolve, reject) => {
			wx.downloadFile({
				url: link,
				success: res => {
					if (res.statusCode === 200) {
						resolve(res.tempFilePath)
					}
				}
			})
		})
	},
	// 生成海报
	draw_poster() {
		const _this = this
		const cardInfo = this.data.cardInfo
		const ctx = wx.createCanvasContext('myCanvas')

		const poster_bg_url = 'https://ii.sinelinked.com/miniProgramAssets/poster_bg.png'
		const poster_01_url = 'https://ii.sinelinked.com/miniProgramAssets/poster_01.png'
		const poster_02_url = 'https://ii.sinelinked.com/miniProgramAssets/poster_02.png'
		const poster_03_url = 'https://ii.sinelinked.com/miniProgramAssets/poster_03.png'

		wx.showLoading({
			title: '海报合成中...',
		})

		let poster_bg, poster_01, poster_02, poster_03 //网络图片需要下载后使用
		_this.downloadImg(poster_bg_url)
			.then(poster_bg => {
				poster_bg = poster_bg
				_this.downloadImg(poster_01_url)
					.then(poster_01 => {
						poster_01 = poster_01
						_this.downloadImg(poster_02_url)
							.then(poster_02 => {
								poster_02 = poster_02
								_this.downloadImg(poster_03_url)
									.then(poster_03 => {
										poster_03 = poster_03
										// 头像
										wx.getImageInfo({
											src: cardInfo.cardHeadUrl,
											success: cardHeadUrlRes => {
												const cardHeadUrl = cardHeadUrlRes.path
												console.log(cardInfo.cardOssQrcode);
												// 太阳码
												wx.getImageInfo({
													src: cardInfo.cardOssQrcode,
													success: cardOssQrcodeRes => {
														console.log(cardOssQrcode);
														const cardOssQrcode = cardOssQrcodeRes.path
														// 绘制白色背景
														ctx.rect(0, 0, 320, 411)
														ctx.setFillStyle('#ffffff')

														// 绘制背景
														ctx.drawImage(poster_bg, 0, 0, 320, 437)
														ctx.save()

														// 绘制头像背景
														ctx.beginPath()
														ctx.arc(75, 97, 52, 0, 2 * Math.PI, false)
														ctx.setFillStyle('#fff')
														ctx.fill()

														// 绘制头像图片
														ctx.beginPath()
														ctx.arc(75, 97, 50, 0, 2 * Math.PI, false)
														ctx.fill()
														ctx.clip()
														ctx.drawImage(cardHeadUrl, 25, 47, 100, 100) // 画 头像
														ctx.restore()

														// 绘制昵称
														ctx.setFillStyle('#333')
														ctx.font = 'normal normal 18px sans-serif';
														ctx.fillText(cardInfo.cardName, 140, 110)

														// 绘制电话
														ctx.font = 'normal bold 16px sans-serif';
														ctx.fillText(cardInfo.cardPhone, 140, 140)

														// 绘制企业信息
														ctx.drawImage(poster_01, 34, 173, 16, 16)
														ctx.font = 'normal normal 13px sans-serif';
														ctx.fillText(cardInfo.cardCompany, 60, 186)

														// 绘制企业信息
														ctx.drawImage(poster_02, 34, 213, 16, 16)
														ctx.font = 'normal normal 13px sans-serif';
														ctx.fillText(cardInfo.cardEmail, 60, 226)

														// 绘制企业信息
														ctx.drawImage(poster_03, 34, 253, 16, 16)
														ctx.font = 'normal normal 13px sans-serif';
														ctx.fillText(cardInfo.cardAddress, 60, 266)

														// 绘制太阳码
														ctx.beginPath()
														ctx.setFillStyle('#fff')
														// ctx.arc(155, 340, 60, 0, 2 * Math.PI, false)
														// ctx.fill()
														// ctx.clip()
														ctx.drawImage(cardOssQrcode, 105, 290, 110, 110)
														ctx.restore()
														ctx.draw()

														wx.hideLoading()

														setTimeout(() => {
															wx.canvasToTempFilePath({
																canvasId: 'myCanvas',
																success: function(res) {
																	_this.setData({
																		poster_image: res.tempFilePath,
																		poster: true
																	})
																}
															})
														}, 500)
													}
												})
											}
											
										})
									})
							})
					})
			})



	},
	// 隐藏海报
	close_poster() {
		this.setData({
			poster: false
		})
	},
	// 显示海报
	renderPoster() {
		const _this = this
		wx.canvasToTempFilePath({
			canvasId: 'myCanvas',
			success: function(res) {
				_this.setData({
					poster_image: res.tempFilePath,
					poster: true
				})
			}
		})
	},
	// 保存图片
	saveImage() {
		const _this = this
		wx.canvasToTempFilePath({
			canvasId: 'myCanvas',
			success: function(res) {
				wx.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success(result) {
						wx.showToast({
							title: '图片保存成功',
							icon: 'success',
							duration: 2000
						})
						_this.setData({
							poster: false
						})
					}
				})
			}
		})
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function(options) {
		this.setData({
			visibleTeamChoose: false
		})
		var cardId = this.data.cardId
		if (cardId) {
			if (JSON.stringify(this.data.cardInfo) == "{}") {
				this.getInfo(cardId, 1)
				this.getInfo(cardId, 4)
			}

		}

		wx.setStorageSync('userType', 'person')
	},
	onReady() {

	},
	onError: function(msg) {
		console.log(msg)
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		this.counter(3)
		return {
			title: this.data.cardForwardTitle || '',
			path: '/pages/card/person/index/index?cardId=' + this.data.cardInfo.id,
			imageUrl: this.data.cardForwardCoverUrl
		}
	}
})
